from pyson.gen import PysonObject, array, string, boolean, struct
from pyduct.handlers import *
from scala import Option
from scaladuct.l10n import CompleteHasHintsMetaDataSource, PropertyValueMeta

NONE = Option.apply(None)

class ListItems(PysonObject):
    data = array(array.elem(string))
    editable = boolean()
    multiChoice = boolean()

class ListItemsHolder(PysonObject):
    ListItems = struct(ListItems)

class CookieListItemsBuilder(CookieFragmentBuilder):

    def getCookieMessageFragmentClass(self, cookieGateway, property):
        listsManagerOpt = cookieGateway.pageExtension(classOf("scaladuct.lists.ListsManager"))
        if listsManagerOpt is not NONE:
            listForPropertyOpt = listsManagerOpt.get().listForProperty(property)
            if listForPropertyOpt is not NONE:
                class Fragment(ListItemsHolder, MessageFragment):
                    def __init__(self):
                        super(Fragment, self).__init__()
                        listForProperty = listForPropertyOpt.get()
                        self.ListItems.editable = listForProperty.editable()
                        self.ListItems.multiChoice = listForProperty.multiChoice()

                        items = ()
                        itemsIterator = listForProperty.content().iterator()
                        while itemsIterator.hasNext():
                            item = itemsIterator.next()
                            val = "%s" % item
                            mtdSourceOpt = cookieGateway.pageExtension(classOf("scaladuct.l10n.HasHintsMetaDataSource"))
                            if mtdSourceOpt is not NONE:
                                mtdSource = mtdSourceOpt.get()
                                mtdForValue = PropertyValueMeta(mtdSource, cookieGateway.locale(), \
                                listForProperty.property().update(item))
                                items += ((val, mtdForValue.title(val), mtdForValue.description("")), )
                            else:
                                items += ((val, "", ""), )

                        self.ListItems.data = items

                return Fragment
            else:
                return None
        else:
            return None

def getBuilders():
    return (CookieListItemsBuilder,)